﻿using System;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace SiteUnity.Frame.Common.Tools.Data
{
    public static class Cache
    {
        public static void AddIfNotExists<T,T2>(string key, out T value,T2 provider, string methodName, object[] arguments)
        {
            if (Exists(key))
                value = (T)HttpContext.Current.Cache[key];
            else
            {
                value = (T)typeof(T2).GetMethod(methodName).Invoke(provider, arguments);
                Add(key, value);
            }
        }

        //static long size = 0;
        public static void Add<T>(string key, T value)
        {
            //using (Stream s = new MemoryStream())
            //{
            //    BinaryFormatter formatter = new BinaryFormatter();
            //    formatter.Serialize(s, value);
            //    size += s.Length;
            //}

            if (!Exists(key))
                HttpContext.Current.Cache.Insert(
                    key,
                    value,
                    null,
                    DateTime.Now.AddMinutes(1440),
                    System.Web.Caching.Cache.NoSlidingExpiration);
            else
                HttpContext.Current.Cache[key] = value;

        }
        
        public static void Clear(string key)
        {
            HttpContext.Current.Cache.Remove(key);
        }

        public static bool Exists(string key)
        {
            return HttpContext.Current.Cache[key] != null;
        }

        public static bool Get<T>(string key, out T value)
        {
            value = Activator.CreateInstance<T>();

            if (!Exists(key))
                return false;

            value = (T)HttpContext.Current.Cache[key];

            return true;
        }
    }
}
